/*
 * drv8305.c
 *
 *  Created on: 2024年10月8日
 *      Author: zizhong
 */

#include "drv8305.h"

uint16_t DRV8305_buildCtrlWord(const uint16_t ctrlMode,
                                             const DRV8305_Address_e regAddr,
                                             const uint16_t data)
{
    uint16_t ctrlWord = ctrlMode | regAddr | (data & DRV8305_DATA_MASK);

  return(ctrlWord);
} // end of DRV8305_buildCtrlWord() function


uint16_t DRV8305_readSPI(uint32_t spiBase,
                         const DRV8305_Address_e regAddr,
                         uint16_t CS_PIN,
                         uint16_t * rxTimeOutFlag)
{
    uint16_t ctrlWord;
    uint16_t n;
    const uint16_t data = 0;
    volatile uint16_t readWord;
    volatile uint16_t WaitTimeOut = 0;
    *rxTimeOutFlag = 0;

    volatile SPI_RxFIFOLevel RxFifoCnt = SPI_FIFO_RXEMPTY;

    // build the control word
    ctrlWord = (uint16_t)DRV8305_buildCtrlWord(DRV8305_CTRLMODE_READ, regAddr, data);

    // reset the Rx fifo pointer to zero
    SPI_resetRxFIFO(spiBase);
    SPI_enableFIFO(spiBase);

    GPIO_writePin(CS_PIN, 0);

    // wait for registers to update
    for(n = 0; n < 0x06; n++)
    {
        __asm(" NOP");
    }

    // write the command
    SPI_writeDataBlockingNonFIFO(spiBase, ctrlWord);

    // wait for two words to populate the RX fifo, or a wait timeout will occur
    while(RxFifoCnt < SPI_FIFO_RX1)
    {
        RxFifoCnt = SPI_getRxFIFOStatus(spiBase);

        if(++WaitTimeOut > 0xffe)
        {
            *rxTimeOutFlag = 1;
        }
    }

    WaitTimeOut = 0xfff;

    GPIO_writePin(CS_PIN, 1);

    // Read the word
    readWord = SPI_readDataNonBlocking(spiBase);

    return(readWord & DRV8305_DATA_MASK);
} // end of DRV8323_readSPI() function

